import { IEvent, IFilesState, IFile } from "./model";
import { loadFile, loadFolder, getName, isSubPath } from "../utils/file-util";

function init (): IFilesState {
  return {
    folders: []
  };
}

function updateFolder (folder: IFile, newFolder: IFile): IFile {
  if (isSubPath(folder.filePath, newFolder.filePath)) {
    return {
      ...folder,
      children: folder.children.map(o => updateFolder(o, newFolder))
    }
  } else if (folder.filePath == newFolder.filePath) {
    return newFolder;
  } else {
    return folder;
  }
}

function onFolderLoad (e: IEvent, s: IFilesState): IFilesState {
  const folder: IFile = e.data;
  const list = loadFolder(folder.filePath);
  const newFolder: IFile = {
    ...folder,
    isLoaded: true,
    children: list.map(o => ({
      filePath: o.path,
      name: o.name,
      isLoaded: false,
      isFolder: o.isFolder,
      children: null,
      content: null,
    })),
  };

  return {
    ...s,
    folders: s.folders.map(o => updateFolder(o, newFolder))
  };
}

function onFolderOpen (e: IEvent, s: IFilesState): IFilesState {
  const folderPath: string = e.data;
  if (!s.folders.find(o => o.filePath == folderPath)) {
    return {
      ...s,
      folders: [
        ...s.folders,
        {
          filePath: folderPath,
          name: getName(folderPath),
          isLoaded: false,
          isFolder: true,
          children: null,
          content: null,
        }
      ]
    }
  } else {
    return s;
  }
}

export function dispatch (e: IEvent, s: IFilesState): IFilesState {
  if (e.type == 'app.init') {
    return init();
  } else if (e.type == 'folder.load') {
    return onFolderLoad(e, s);
  } else if (e.type == 'folder.open') {
    return onFolderOpen(e, s);
  } else {
    return s
  }
}
